package com.clp.protocol.iec104.iec104.apdu.asdu.infoobj.infoelem.filetransfer;

import com.clp.protocol.iec104.iec104.definition.Ft;
import com.clp.util.StringUtil;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.Objects;

/**
 * 读文件激活 附加数据包
 */
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class FileReadActAttachPack extends AttachPack {
    @Override
    public Ft.OperationTag operationTag() {
        return Ft.OperationTag.FILE_READ_ACT;
    }

    /**
     * 文件名长度
     */
    private int filenameBytesLen;

    /**
     * 文件名
     */
    private String filename;

    @Override
    public FileReadActAttachPack refreshFrom(ByteBuf buf) {
        checkOperationTag(buf.readByte());
        // 文件名长度
        this.filenameBytesLen = buf.readByte() & 0xFF;
        // 文件名
        byte[] filenameBytes = new byte[filenameBytesLen]; buf.readBytes(filenameBytes);
        this.filename = StringUtil.decode(filenameBytes, "utf-8");
        return this;
    }

    @Override
    public boolean isValid() {
        if (filenameBytesLen < 0 || filenameBytesLen > 0xFF) return false;
        return filename != null && !filename.equals("");
    }

    @Override
    public void writeBytesTo(ByteBuf buf) {
        // 填写操作标识
        buf.writeByte(operationTag().getVal());
        // 文件名长度
        byte[] filenameBytes = StringUtil.encode(filename, "utf-8");
        buf.writeByte(filenameBytes.length);
        // 文件名
        buf.writeBytes(filenameBytes);
    }

    @Override
    public String toString() {
        return "文件名字节长度：" + filenameBytesLen + ", 文件名：" + filename;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        FileReadActAttachPack that = (FileReadActAttachPack) o;
        return filenameBytesLen == that.filenameBytesLen && Objects.equals(filename, that.filename);
    }

    @Override
    public int hashCode() {
        return Objects.hash(filenameBytesLen, filename);
    }
}
